#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
#include "wificonfig.h"

const char* mqttServer = "192.168.121.156";
const char* topic_temp = "hqyjxa/sensor/temp";
const char* topic_humi = "hqyjxa/sensor/humi";
const char* will_topic = "hqyjxa/sensor/online";
unsigned long prev_millis = 0;

DHT dht(D1, DHT11);
WiFiClient wificlient;
PubSubClient client(mqttServer, 1883, wificlient);

void setup() {
    Serial.begin(115200);
    autoConfig();
    dht.begin();
}

void loop() {
    if (!client.connected()) {
        //连接MQTT代理，客户端ID，用户名，密码，遗嘱主题，遗嘱QoS，遗嘱保留，遗嘱内容
        //连接成功后，将online主题（遗嘱）设置为1，表示设备上线，订阅者收到通知
        //连接非正常断开后，online内容会被代理设置为0，表示设备下线，订阅者收到通知。
        //https://pubsubclient.knolleary.net/api.html
        if (client.connect(clientID().c_str(), NULL, NULL, will_topic, 1, 1, "0")) {
            Serial.println(clientID() + " connected");
            client.publish(will_topic, "1", true);
            digitalWrite(LED_BUILTIN, LOW); //LED On
        } else {
            Serial.print("connect failed ");
            Serial.print(client.state());
            Serial.println(", try again in 1 second");
            digitalWrite(LED_BUILTIN, HIGH); //LED Off
            delay(1000);
            return;
        }
    }
    client.loop();

    if (millis() - prev_millis < 60000) {//每分钟获取一次温湿度信息
        return;
    }
    prev_millis = millis();

    float h = dht.readHumidity();
    float t = dht.readTemperature();
    if (isnan(h) || isnan(t)) {
        Serial.println("Failed to read from DHT sensor!");
        return;
    }

    client.publish(topic_temp, String(t).c_str(), true);
    client.publish(topic_humi, String(h).c_str(), true);
}
